package com.equipment.user.web.web.interceptor;

import com.equipment.user.web.web.annotation.ApiDecrypt;
import com.equipment.user.web.web.security.Base64Helper;
import com.equipment.user.web.web.security.RSAUtils;
import com.equipment.user.web.web.security.RsaHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.PrivateKey;

/**
 * ${DESCRIPTION}
 *
 * @author 杨凯
 * @create 2018-03-26 8:55
 **/
public class EncryptInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(EncryptInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			ApiDecrypt annotation = method.getAnnotation(ApiDecrypt.class);
			if (annotation != null) {
				boolean needDecrypt = annotation.decrypt();
				if (needDecrypt) {
					InputStream in = request.getInputStream();
					StringBuffer sb = new StringBuffer();
					byte[] b = new byte[1024];
					int len = 0;
					try
					{
						while ((len = in.read(b)) != -1)
						{
							sb.append(new String(b, 0, len, "utf-8"));
						}
						String value = decrypt(sb.toString());
						request.setAttribute("value",value);
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			}
			return true;
		} else {
			return super.preHandle(request, response, handler);
		}
	}


	/**
	 * 解密数据
	 *
	 * @param encryptContent 要解密的数据
	 */
	public String decrypt(String encryptContent) {
		try {
			// 从文件中得到私钥
			File file = ResourceUtils.getFile("classpath:rsa_private_key_pkcs8.pem");
			InputStream inPrivate = new FileInputStream(file);
			PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
			String rs = new String(RsaHelper.decryptData(
					Base64Helper.decode(encryptContent), privateKey), "UTF-8");
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
